define(function (require, exports, module) {
    // require('./plug/hammer.min');
    // require('./plug/lazyload_echo');
    // require('./plug/layer/layer');
    var myPub = require('./public');


    //产品懒加载  异步加载 调用这个
    myPub.lazLoadingImgEcho();

	//导航点击
    var sign = ['all','wait4Payment','wait4Delivery','wait4Receive','tradeSuccess'];//全局 订单类型
    var dataLoadCount = [0,0,0,0,0];	//点击导航   没点击导航时初始值为0  点击一次后加1
    var order_scrollTop = [];


    var oOrderListNav = $('.js_orderListNav');  		//订单导航
    var oOrderSlideList = $('.js_orderSlideList')		//订单列表
    var iNow = 0;	//对应订单导航的索引


    //设置页面滚动高度
    if(sessionStorage.getItem("order_scrollTop") !== null  ) {
		var _indexScrollTop = sessionStorage.getItem("order_scrollTop").split(',');
    	for(var i=0; i<_indexScrollTop.length; i++) {
    		order_scrollTop[i] = _indexScrollTop[i];
    	}

    }
	else {
		order_scrollTop = [0,0,0,0,0];
	}


    module.exports = {
        init: function (data,name,count) {
            //console.log(data);
			//点击我的信息 导航
			if(localStorage.getItem("orderNav_index") != null) {
        		var getIndex = parseInt( localStorage.getItem("orderNav_index") );
        		iNow = getIndex;
        	}
			//点击查看更多
        	else {
        		iNow = 0;
        	}

        	HistoryDataNum (function(loadNum) {
        		//console.log(loadNum)
        		SetOrderNav(data,name,count,function() {
	            	oOrderListNav.find('li').eq(iNow).addClass('active');
	            	//页面第一次加载 all  全部订单
		            loadPageData(iNow,loadNum[iNow]);
		            //初始加载  相当于点击了全部点击一次导航   该导航点击的得次数为1
		            dataLoadCount[iNow] = 1;

	            });
        	})

        }
    };



    //定位页面跳转后滚动距离
	$(window).unload(function(){
		setBeforIndexScrollTop();
	});




	var oMoreBtn = $(".js_moreBtn");		//显示更多按钮
    var oNoMoreBtn = $(".js_nomore");		//没有更多按钮
    var oLoadingBtn = $(".js_loadingBtn");	//加载中
    var oContain = $(".js_contain");		//页面主题
    var oMyOrderList = $('.js_myOrderList');//订单列表主题
    var oErrPage = $(".js_errPage"); 		//错误页面

    //ajax 分页加载数据
    var dataNav = [0,0,0,0,0];//初始数组    表示 每个类型的订单加载的初始个数
    var dataNavBoolean = [false,false,false,false,false];//表示每个类型的订单的初始状态  false表示有数据可加载  true表示没有查到数据
    var limit = 10;

   	//导航点击
    oOrderListNav.hammer().on('tap', function (e) {
    	setBeforIndexScrollTop();
        var _tar = e.gesture.target;
        var $target;
        var oOrderListSlide = $('.js_orderListSlide')	//订单页面

        _tar.nodeName.toLowerCase() == 'li' ? $target = $(_tar) : $target = $(_tar).parents('li');

        var index = $target.index();
        iNow = index;

        //点击导航  分页查询数据
        if(dataLoadCount[index] == 0){
            oMoreBtn.hide();
            oNoMoreBtn.hide();
        }else if(dataLoadCount[index] > 0 && dataNavBoolean[index] == true){
            oMoreBtn.hide();
            oNoMoreBtn.show();
        }else if(dataLoadCount[index] > 0 && dataNavBoolean[index] == false){
            oMoreBtn.show();
            oNoMoreBtn.hide();
        }

		HistoryDataNum (function(loadNum) {
    		//页面第一次加载 all  全部订单
            loadPageData(iNow,loadNum[iNow]);

            //点击一次导航   该导航点击的得次数为1
            dataLoadCount[iNow] = 1;
            oOrderListNav.find('li').removeClass('active').eq(iNow).addClass('active');

            HistoryScrollY(iNow);

	        //产品懒加载  异步加载 调用这个
	        myPub.lazLoadingImgEcho();

	        //设置本地存储 对应导航位置
	        localStorage.setItem("orderNav_index",iNow);
   		});

    });


    //显示更多
    oMoreBtn.hammer().on('tap', function () {
        var _this = $(this);
        _this.hide().siblings('.js_loadingBtn').show().find('.icoStyle').addClass('myRotateRefresh');

        //点击加载更多 需要 把dataLoadCount[index] 变成0
        dataLoadCount[iNow] = 0;

        //并排li
        setTimeout(function () {
            loadPageData(iNow,limit,function() {
            	//设置显示多少数据
                sessionStorage.setItem("order_loadNum", dataNav);
            });

            //加载后 再次把dataLoadCount[index] 变成1 //点击一次导航   该导航点击的得次数为1
            dataLoadCount[iNow] = 1;

            _this.show().siblings('.js_loadingBtn').hide().find('.icoStyle').removeClass('myRotateRefresh');

            //产品懒加载  异步加载 调用这个
            myPub.lazLoadingImgEcho();
            //$(window).scrollTop() + loadGoHeight
        }, 1000)

        myPub.HamstopPropaga()
    });

    //页面滚动历史高度
    function HistoryScrollY(index) {
    	if(sessionStorage.getItem("order_scrollTop") !== null  ) {
    		var _indexScrollTop = sessionStorage.getItem("order_scrollTop").split(',')[index]
	    	var _scrollTop = parseInt( _indexScrollTop )
	    	//console.log( 'index：'+index +'， _scrollTop: '+ _scrollTop)
	    	$(window).scrollTop( _scrollTop )
	    }
    }

    //获取历史数据
    function HistoryDataNum (fn) {
		var loadNum = [limit,limit,limit,limit,limit]
	    if(sessionStorage.getItem("order_loadNum") !== null  ) {
	    	var getOrder_loadNum = sessionStorage.getItem("order_loadNum").split(',')
	    	for(var i=0; i<getOrder_loadNum.length; i++) {

	    		if( parseInt(getOrder_loadNum[i]) < limit) {
	    			loadNum[i] = limit
	    		}
	    		else {
	    			loadNum[i] = parseInt(getOrder_loadNum[i])
	    		}

	    	}
	    }
	    if(fn)fn(loadNum)
	}

    //记录切换前的页面位置
    function setBeforIndexScrollTop(fn) {
		oOrderListNav.find('li').each(function(i) {
			if(oOrderListNav.find('li').eq(i).hasClass('active')) {
				order_scrollTop[i] = $(window).scrollTop();
			}
		});

		//console.log($(window).scrollTop())
		sessionStorage.setItem("order_scrollTop", order_scrollTop);

		if(fn)fn();
	}

    //加载数据
    function loadPageData(index,limit,fn) {
		var oOrderListSlide = $('.js_orderListSlide')	//订单页面

        oOrderListSlide.hide().eq(index).show();;
        oErrPage.hide();
        oMyOrderList.show();

        if(dataLoadCount[index] > 0 && dataNav[index] != 0){
            return;
        }

        if(dataNavBoolean[index] == true && dataNav[index] != 0){
            return;
        }



        G_JSON_POST('/member/order/showTypePayment',{
        	"type": sign[index],
        	"start": dataNav[index],
        	"limit":limit
        },function(data){
            if (data.status == "success") {
                var length = data.orderList.length;

                //加载数据的个数
                dataNav[index] += length;

                if(length < limit ){
                   //当查询到的数据  小于分页的limit值时  显示没有更多
                    dataNavBoolean[index] = true;
                    if(dataNav[index] == 0){
                        //首次加载完成后   dataNav[index] = 0 代表没有数据 显示errorPage
                        oLoadingBtn.hide();
                        oMoreBtn.hide();
                        oNoMoreBtn.hide();
                        oMyOrderList.hide();
                        oErrPage.show();

                        //dataLoadCount[index] = 0;

                    }else{
                        //首次加载后有数据 但是小于limit  显示没有更多
                        //oMyOrderList.show();
                        oLoadingBtn.hide();
                        oMoreBtn.hide();
                        oNoMoreBtn.show();
                    }

                }
                else{
                    //oMyOrderList.show();
                    oMoreBtn.show();
                    //oLoadingBtn.show();
                    oNoMoreBtn.hide();
                }
                for ( var i = 0; i < length; i++) {
                    var order = data.orderList[i];
                    var seller = data.supplierMap[order.supplierId];
                    var goodsId = order.goodsIds;
                    var goods = data.goodsMap[goodsId];

                    addOrderHtml(order,seller,goods,index);

                }
                myPub.lazLoadingImgEcho();
                HistoryScrollY(index)
                if(fn)fn()
            }else {
                myPub.TipLayer(data.message);
            }

        });
    }

    //设置导航
	function SetOrderNav(name, iconClass, count, callBack) {
		//'<li class="Bflex1"><em class="icoStyle icon_WaitPay"><i class="record">9</i></em><span>待付款</span><em class="splitline"></em></li>'

		for(var i = 0; i<name.length; i++) {

			oOrderListNav.find('ul').append('<li class="Bflex1"><em class="icoStyle '+ iconClass[i] +'">'+ CountNum(count[i]) + '</em><span>'+ name[i] +'</span><em class="splitline"></em></li>')

			oOrderSlideList.append('<section class="orderList js_orderListSlide"></section>')

		}

		if(callBack)callBack();
	}

	//设置角标
	function CountNum(obj) {
		var _obj = parseInt(obj);
		if(_obj >99){
            _obj = 99+"+";
        }
		if(_obj == 0) {
			return ''
		}
		else {
			return '<i class="record">' + _obj + '</i>'
		}
	}


/***************************************   操作按钮点击          ***************************************************/


    var oContactBossBtn = $('.js_contactBoss');     		//联系商家信息按钮 js_contactBoss
    var oBossInfo = $('.js_bossInfo');              		//商家信息 js_bossInfo
    var oBossName = $('.js_bossName');              		//店家名字
    var oReasonList = $('.js_reasonList');          		//取消原因选择
    var oCanOrderBtn = $('.js_cancelOrderBtn');     		//取消订单按钮
    var oCanOrderInfo = $('.js_cancelOrder');       		//取消订单信息
    var oUserMessage = $('.js_message').find('textarea');  	//留言区域
    var oTrueGetBtn = $('.js_trueGetBtn');          		//确认收货
    var oDelOrderBtn = $('.js_delOrderBtn');        		//删除订单
    var oCancelApply = $('.js_cancelApply');        		//取消申请
    var oMyOrderList = $('.js_myOrderList');

    //用户操作
    oMyOrderList.hammer().on('tap', function (e) {
        //console.log(e.gesture.target)
        var _btnA = $(e.gesture.target);

        var _typeNum = _btnA.attr('_type');
        var oId = _btnA.attr('oId');

        if(_typeNum !== undefined) {
       		myPub.HamstopPropaga();
       	}

        switch (_typeNum * 1) {
            // 0 联系商家
            case 0:
                var styleTitle = 'width:100%;  border:none';
                var _sBossInfo = _btnA.parents('.js_cBossA').siblings('.js_bossInfo');
                var _BossName = $('.js_OrderListHead').find('.js_bossName').text();
                _sBossInfo.show();
                myPub.TipTitleLayer('联系商家： ' + _BossName, styleTitle, _sBossInfo.html(), function () {
                    _sBossInfo.hide();
                });

                break;
            // 1 取消订单
            case 1:
                var styleTitle = '请选择取消原因';
                myPub.askLayer(oCanOrderInfo.html(), function () {
                        var reasonType = $('.js_reasonList').find('li.active').html();
                        var oUserMessage = $('.js_message').find('textarea').eq(1).val();
                        oCanOrderInfo.hide();
                        G_JSON_GET('/member/order/cancel', {
                            "orderId": oId,
                            "reasonType": reasonType,
                            "reason": oUserMessage
                        }, function (data) {
                            if (data.status == "success") {
                                location.reload();
                            } else {
                                myPub.TipLayer(data.message);
                            }
                        });
                    }, function () {
                        oCanOrderInfo.hide();
                    }, styleTitle,
                    function () {
                        oCanOrderInfo.show();
                        // 弹框原因选择
                        var _oReasonListLi = $('.js_reasonList').find('li');
                        var oUserMessage = $('.js_message').find('textarea');  // 留言区域
                        var maxLWord = $('.js_wordmax');               // 最大字数
                        _oReasonListLi.hammer().off('tap');
                        _oReasonListLi.hammer().on('tap', function () {
                            _oReasonListLi.removeClass('active');
                            $(this).addClass('active');
                        });
                        myPub.statInputNum(oUserMessage, maxLWord);
                    });
                break;
            // 2 立即付款
            case 2:
                submitPay(oId);
                // $('<form action="/shop/payment/oneOrder"><input name="orderId" value="'+oId+'"/></form>').submit();
                break;
            // 3 申请售后
            case 3:
                //alert(_typeNum);
                break;
            // 4 查看物流
            case 4:
                window.location.href = "/member/order/express/" + oId;
                break;
            // 5 确认收货
            case 5:
                var _cont = '<p class="delTipP" >亲！ 确定您已收到货物了吗？</p><span class="delTipSpan">确认收货后平台将会将货款打给商家</span>';
                myPub.askLayer(_cont, function () {
                    G_JSON_GET('/member/order/receive', {"orderId": oId}, function (data) {
                        if (data.status == "success") {
                            //location.reload();
                            window.location.href = '/shop/goodsComment/comment/'+oId;
                        } else {
                            myPub.TipLayer(data.message);
                        }
                    });
                    myPub.LayerCloseAll();
                }, function () {
                }, 'no');
                break;
            // 6 删除订单
            case 6:
                var _cont = '<p class="delTipP" >亲！ 您确定要删除此订单吗？</p><span class="delTipSpan">删除后此订单会永远消失</span>';
                myPub.askLayer(_cont, function () {
                    //alert(1)
                    G_JSON_GET('/member/order/delete', {"orderId": oId}, function (data) {
                        if (data.status == "success") {
//                            location.reload();
                        } else {
                            myPub.TipLayer(data.message);
                        }
                    });
                    myPub.LayerCloseAll();
                }, function () {
                    //alert(2)
                }, 'no');
                break;
            // 7 立即评价
            case 7:
            	//先验证是否已经评价过
            	G_JSON_GET('/shop/goodsComment/find_comment/'+oId, null, function (data) {
                    if (data.status == "success") {
                    	window.location.href= "/shop/goodsComment/comment/"+oId;
                    } else {
                        myPub.TipLayer(data.message);
                    }
                });
                //window.location.href= "/shop/goodsComment/comment/"+oId;
                break;
            default:
                ;
                break;
        }
    });

});
